﻿using System.Collections.Generic;
using System.ServiceProcess;
using System.Threading;
using SubmissionsProcessingService.Properties;
using SubmissionsProcessingService.Utils;

namespace SubmissionsProcessingService
{
    public partial class Service1 : ServiceBase
    {
        private readonly List<Worker> m_workers = new List<Worker>();

        public Service1()
        {
            InitializeComponent();

            var processingSubmissionIds = new SynchronizedHashtable();
            for (int i = 1; i <= Settings.Default.ProcessingThreadsCount ; i++)
            {
                var processor = new SubmissionsProcessor(processingSubmissionIds);

                m_workers.Add(new Worker
                {
                    SubmissionsProcessor = processor,
                    WorkerThread = new Thread(processor.ProcessSubmission)
                });
            }
        }

        public void OnDebug()
        {
            OnStart(null);
        }

        protected override void OnStart(string[] args)
        {
            StartProcessingForEachWorker();
        }

        private void StartProcessingForEachWorker()
        {
            foreach (var worker in m_workers)
            {
                worker.WorkerThread.Start();
            }
        }

        protected override void OnStop()
        {
            TryStopWorkers();
        }

        private void TryStopWorkers()
        {
            foreach (var worker in m_workers)
            {
                worker.SubmissionsProcessor.Stop();
            }

            foreach (var worker in m_workers)
            {
                worker.WorkerThread.Join(1000*60);
            }
        }

        private class Worker
        {
            public Thread WorkerThread { set; get; }
            public SubmissionsProcessor SubmissionsProcessor { set; get; }
        }
    }
}
